package main

import (
	"expvar"
	"fmt"
	"net/http"
	"time"
)

var stats = expvar.NewMap("tcp")
var requests expvar.Int

var start = time.Now()

func calculateTime() interface{} {
	return time.Since(start).String()
}

func init() {
	stats.Set("requests", &requests)//为什么是指针，因为requests会后续加1

	//在调用 Var.String()的时候才会调用calculateTime()
	expvar.Publish("calculateTime", expvar.Func(calculateTime))
}

//全局注册expvar.Publish(name, v)
var visits = expvar.NewInt("visits")

func handler(w http.ResponseWriter, r *http.Request) {
	visits.Add(1) //atomic.AddInt64  线程安全
	requests.Add(1)
	fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

// http://localhost:1818/debug/vars
// 通过expvarHandler()来打印expvar.varKeys
func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":1818", nil)
}
